﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using ENICHIUSURA.Utils;
using Logging;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using ENICHIUSURA.Tests;

namespace ENICHIUSURA
{
    public partial class Form1 : Form
    {
        bool started = false;
        public Form1()
        {
           InitializeComponent();
           this.ShowInTaskbar = false;
           this.WindowState = FormWindowState.Minimized;
           // this.Hide();
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Configurazione cf = new Configurazione();
            cf.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void manualeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (VerifyConfig() == true)
            {
                pianificataToolStripMenuItem.Enabled = false;
                manualeToolStripMenuItem.Enabled = false;
                backgroundWorker1.RunWorkerAsync();
            }
            else
                MessageBox.Show("Si prega di compilare tutti i campi di configurazione!");
        }

        private void pianificataToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (VerifyConfig() == true)
            {
            if (pianificataToolStripMenuItem.Text.ToLower().Contains("start"))
            {
                manualeToolStripMenuItem.Enabled = false;
                pianificataToolStripMenuItem.Text = "Pianificata Stop";
                timer1.Enabled = true; //after 60 second the first tick event will be raised
            }
            else //contains STOP
            {
                manualeToolStripMenuItem.Enabled = true;
                pianificataToolStripMenuItem.Text = "Pianificata Start";
                timer1.Stop();
            }
            }
            else 
                MessageBox.Show("Si prega di compilare tutti i campi di configurazione!");
        }
       
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (ConfigUtil.GetHour() == DateTime.Now.Hour.ToString()
                && ConfigUtil.GetMinute() == DateTime.Now.Minute.ToString() && started == false)
            {
                //WrappedAutomation(); //secvential execution
                pianificataToolStripMenuItem.Enabled = false;
                notifyIcon1.Visible = true;
                notifyIcon1.ShowBalloonTip(3000, "ENI CHIUSURA automazione", "Esportazione iniziato.", new ToolTipIcon());
                backgroundWorker1.RunWorkerAsync(); //async execution
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Debug.WriteLine(DateTime.Now.TimeOfDay);
            WrappedAutomation();
            Debug.WriteLine(DateTime.Now.TimeOfDay);
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (pianificataToolStripMenuItem.Enabled == false)
            {
                pianificataToolStripMenuItem.Enabled = true;
                manualeToolStripMenuItem.Enabled = true;
            }
            notifyIcon1.ShowBalloonTip(3000, "ENI CHIUSURA automazione", "Esportazione finito.", new ToolTipIcon());
        }

        //Testing button
        private void button2_Click(object sender, EventArgs e)
        {
            EniTesting.ReadExcelTest(EniTesting.inputFilePath, EniTesting.inputFilename); //OK
           // EniTesting.ArrayToDTTest(EniTesting.inputFilePath, EniTesting.inputFilename); //OK
            //EniTesting.ExportDtToExcel(EniTesting.outputFilepath, EniTesting.outputFileName); //OK
            //EniTesting.RenameOutputFile("input.xls");
        }

        private void WrappedAutomation()
        {
            string inputFilePath = ConfigurationManager.AppSettings["InputFilePath"];
            string inputFilename = ConfigurationManager.AppSettings["InputFileName"];
            notifyIcon1.Visible = true;
            notifyIcon1.ShowBalloonTip(3000, "Eni Chiusura automazione.", "Esportazione iniziato.", new ToolTipIcon());

            started = true;
            Automation au = new Automation();
            if (au.Run(ExcelUtils.GetExcelDT(inputFilePath, inputFilename)) == "OK")//excel file written
            {
                MailUtils.SendMail(ConfigurationManager.AppSettings["Sender"],
                                    ConfigurationManager.AppSettings["StatusEmail"],
                                    "TERMINE LAVORAZIONE ricerca contabili ENI chiusura affidamento ",
                                    " la presente per informarVi che sono state ricercate le copie contabili dell’affidamento chiuso, si prega di verificare il file in allegato per le copie non trovate, inoltre nel seguente percorso "+
                                    ConfigurationManager.AppSettings["OutputFilePath"] + " e’ presente il file contenente quelle trovate.",
                                    Path.Combine( ConfigurationManager.AppSettings["OutputFilePath"] ,
                                     FileUtils.AppendDateToFileName(ConfigurationManager.AppSettings["OutputFileName"])));
            }
            else
            {
                Logger.LogInfo("Excel file not exported");
            }
            started = false;
            Logger.LogInfo("Done with the automation on" + DateTime.Now.ToString());
        }

        private bool VerifyConfig()
        {
            if (
                 String.IsNullOrEmpty(ConfigUtil.GetExcelName())
                || String.IsNullOrEmpty(ConfigUtil.GetExcelPath())
                || String.IsNullOrEmpty(ConfigUtil.GetFirstSearchPath())
                || String.IsNullOrEmpty(ConfigUtil.GetLogFolder())
                || String.IsNullOrEmpty(ConfigUtil.GetOutputFileName())
                || String.IsNullOrEmpty(ConfigUtil.GetOutputFilePath())
                || String.IsNullOrEmpty(ConfigUtil.GetSecondSearchPath())
                || String.IsNullOrEmpty(ConfigUtil.GetSender())
                || String.IsNullOrEmpty(ConfigUtil.GetSenderPassword())
                || String.IsNullOrEmpty(ConfigUtil.GetSMTPPort())
                || String.IsNullOrEmpty(ConfigUtil.GetSMTPServer())
                || String.IsNullOrEmpty(ConfigUtil.GetSSL())
                || String.IsNullOrEmpty(ConfigUtil.GetStatusEmail())
                || String.IsNullOrEmpty(ConfigUtil.GetLogFolder())
                )
                return false;
            return true;
        }
    }
}
